package com.zhou.bjgl.bjgl.business_web.service.listener;


import com.rabbitmq.client.Channel;
import com.zhou.bjgl.bjgl.constants.MqConstant;
import com.zhou.bjgl.bjgl.business_web.entity.MailForm;
import com.zhou.bjgl.bjgl.req.user.UserReq;
import com.zhou.bjgl.bjgl.business_web.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: MailListenerService
 * @Description:
 * @Author: zhou
 * @Date: 2022/2/26 20:45
 */
@Service
public class MailListener {
    private final Logger LOG= LoggerFactory.getLogger(MailListener.class);

    @Resource
    private MailService mailService;

    @RabbitListener(queues = MqConstant.MAIL_REGISTER_QUEUE)
    public void sendRegisterMail(Message message, Channel channel, UserReq req) throws IOException {
        LOG.info("为用户发送修改后密码:[{}]", req.getPassword());

        try {
            MailForm mailForm = new MailForm();
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("username", req.getUsername());
            userMap.put("password", req.getPassword());
            mailForm.setTo(Arrays.asList(req.getEmail())).setSubject("密码修改通知").setTemplateName("changePassword").setText(req.getPassword())
                    .setContextVar(userMap);
            mailService.sendTemplateMail(mailForm);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            LOG.info("邮件发送成功");
        } catch (IOException e) {
            LOG.error("邮件发送失败", e.getMessage());
            // 回复消息处理失败，并重新入队
            // channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
//            throw new CustomException(ResultCodeEnum.MAIL_SEND_FAILED);
        }
    }
}
